<script setup>
import { loginApi } from '@/api/manager'
import { ElNotification } from 'element-plus'
import { ref } from 'vue'
import { setToken } from '@/utils/cookie'
import { useRouter } from 'vue-router'
import useUserStore from '@/store/user'

const router = useRouter()
const form = ref({
  username: 'admin',
  password: 'admin'
})
const loading = ref(false)
const formRef = ref(null)
const userStore = useUserStore()
const rules = {
  username: [{ required: true, message: '用户名不能为空', trigger: 'blur' }],
  password: [{ required: true, message: '密码不能为空', trigger: 'blur' }]
}

const onLogin = async () => {
  const val = await formRef.value.validate((val) => val)
  if (!val) return false

  loading.value = true

  loginApi(form.value.username, form.value.password)
    .then((res) => {
      //登录成功提示
      ElNotification({
        message: '登录成功',
        type: 'success',
        duration: 3000
      })
      //存储token
      setToken(res.token)

      //路由跳转到后台首页
      router.push('/')
    })
    .finally(() => [(loading.value = false)])
}
</script>

<template>
  <el-row class="login-container">
    <el-col :span="16" class="left">
      <div>
        <div class="title">欢迎光临</div>
        <div class="text-light-50">
          此站点是《vue3+vite实战商城后台开发》视频课程的演示地址， 点击立即学习
        </div>
      </div>
    </el-col>
    <el-col :span="8" class="right">
      <h2 class="title">欢迎回来</h2>
      <div class="tip">
        <span class="border"></span>
        <span>账号密码登录</span>
        <span class="border"></span>
      </div>
      <el-form :model="form" class="w-[250px]" :rules="rules" ref="formRef">
        <el-form-item prop="username">
          <el-input v-model="form.username" prefix-icon="User" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="form.password"
            prefix-icon="Lock"
            placeholder="请输入密码"
            type="password"
            show-password
          />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            round
            color="#626aef"
            class="w-[250px]"
            @click="onLogin"
            :loading="loading"
            >登录</el-button
          >
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
</template>

<style scoped>
.login-container {
  @apply bg-indigo-500 min-h-screen;
}

.login-container .left,
.login-container .right {
  @apply flex items-center justify-center;
}

.login-container .right {
  @apply flex-col bg-light-50;
}

.login-container .right .title {
  @apply font-bold text-3xl text-gray-800;
}

.login-container .right .tip {
  @apply flex items-center justify-center my-5 text-gray-500 space-x-2;
}

.login-container .right .tip .border {
  @apply h-[1px] w-16 bg-gray-200;
}

.login-container .left .title {
  @apply font-bold text-5xl text-light-50 mb-4;
}
</style>
